import {Component, TemplateRef, ViewChild} from '@angular/core';
import {
  NzDropdownContextComponent,
  NzDropdownService,
  NzFormatEmitEvent,
  NzTreeComponent,
  NzTreeNode
} from 'ng-zorro-antd';
import { SystemConfigService } from '@core/services/system-config.service';

@Component({
  selector: 'app-departments-list',
  templateUrl: './departments-list.component.html',
  styleUrls: ['./departments-list.component.less']
})
export class DepartmentsListComponent {

  @ViewChild('treeCom') treeCom: NzTreeComponent;
  dropdown: NzDropdownContextComponent;
  // actived node
  activedNode: NzTreeNode;
  public nodes: any;
  public treeData: any;
  public isVisible = false;
  public isConfirmLoading = false;
  public leadList: any;
  public total: any = 0;
  public pageIndex: any = 1;
  public pageSize: any = 10;
  public tableId: any;
  public tableName: any;
  public deptModInfos: any = {
    id: '',
    leader: '',
    name: '',
    parentId: '',
    remark: '',
    sort: '',
  };
  public tableInfos: any;

  constructor( private systemService: SystemConfigService, private nzDropdownService: NzDropdownService ) { }

  openFolder(data: NzTreeNode | NzFormatEmitEvent): void {
    // do something if u want
    if (data instanceof NzTreeNode) {
      data.isExpanded = !data.isExpanded;
    } else {
      data.node.isExpanded = !data.node.isExpanded;
    }
  }

  activeNode(data: NzFormatEmitEvent): void {
    this.activedNode = data.node;
    this.tableId = this.activedNode.origin.key;
    this.tableName = this.activedNode.origin.name;
    this.tableInit(this.tableId, this.tableName);
    console.log(data);
  }

  contextMenu($event: MouseEvent, template: TemplateRef<void>): void {
    this.dropdown = this.nzDropdownService.create($event, template);
  }

  selectDropdown(): void {
    this.dropdown.close();
    // do something
  }

  // 把菜单数据处理成树形结构
  createTreeData(data) {
    this.treeData = [];
    if (data.length > 0) {
      for (const n of data) {
        if (!n.parent) {
          const obj: any = {
            title: n.text,
            key: n.id,
            name: n.name,
            sort: n.sort,
            id: n.id
          };
          this.treeData.push(obj);
        }
      }

      this.run(data, this.treeData);
    }
    return this.treeData;
  }

  run(resData, chiArr) {
    if (resData.length !== 0) {
      if (chiArr) {
        for (const value of chiArr) {
          for (const value2 of resData) {
            if (value.id === value2.parent) {
              const obj = {
                title: value2.text,
                key: value2.id,
                name: value2.name,
                sort: value2.sort,
                id: value2.id
              };
              if (!value.children) {
                value.children = [];
              }
              value.children.push(obj);
            }
          }
          this.run(resData, value.children);
        }
      }
    }
  }

  // 新增修改模态框
  showModal(id, type): void {
    if (this.dropdown) {
      this.dropdown.close();
    }
    this.isVisible = true;

    // 新增id为null
    if (id == null) {
      this.deptModInfos = {
        leader: ''
      };
      this.deptModInfos.id = null;
      if (type == null) {
        // 重新渲染树状图
        this.ngOnInit();
      }

      // 不同点击方式的上级部门赋值
      if (type == 1) {
        this.deptModInfos.parentId =  this.activedNode.origin.key;
        this.deptModInfos.parentName = this.activedNode.origin.name;
      } else if (type == 2) {
        this.deptModInfos.parentId = this.activedNode.parentNode ? this.activedNode.parentNode.key : '';
        this.deptModInfos.parentName = this.activedNode.parentNode ? this.activedNode.parentNode.origin.name : '';
      } else if (type == 3) {
        this.deptModInfos.parentId = this.tableId;
        this.deptModInfos.parentName = this.tableName == '部门列表' ? '' : this.tableName;
      } else {
          this.deptModInfos.parentId = '';
          this.deptModInfos.parentName = '';
        }
    } else {
      this.systemService.depTreeDetail(this.activedNode.origin.key).then(
        (response: any) => {
          this.deptModInfos = response.data;
          if (this.deptModInfos.parentId == null) {
            // 重新渲染树状图
            this.ngOnInit();
          }
        },
        reject => {
          console.log(reject);
        }
      );
    }

    this.systemService.selCom('tb_sys_staff').then(
      (response: any) => {
        this.leadList = response.data.content;
      },
      reject => {
        console.log(reject);
      }
    );
  }

  handleOk(): void {
    this.isConfirmLoading = true;

    const params = {
      id: this.deptModInfos.id,
      leader: this.deptModInfos.leader,
      name: this.deptModInfos.name,
      parentId: this.deptModInfos.parentId,
      remark: this.deptModInfos.remark,
      sort: this.deptModInfos.sort
    };
    console.log(params);
    this.systemService.depTreeMod(params).then(
      (response: any) => {
        this.isVisible = false;
        this.isConfirmLoading = false;
        this.ngOnInit();
      },
      reject => {
        console.log(reject);
      }
    );
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  deptDel() {
    this.systemService.depTreeDel(this.activedNode.origin.key).then(
      (response: any) => {
        this.ngOnInit();
        this.dropdown.close();
      },
      reject => {
        console.log(reject);
      }
    );
  }

  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
    if (event.keys.length == 0) {
      this.deptModInfos.parentId = null;
      this.deptModInfos.parentName = '';
    } else {
      this.deptModInfos.parentId = event.node.key;
      this.deptModInfos.parentName = event.node.origin.name;
    }
  }

  expanded(item) {
    if (item.children) {
      item.expanded = true;
      item.children.map((value: any) => {
        this.expanded(value);
      });
    } else {
      item.isLeaf = true;
    }
    return item;
  }

  tableInit(id, name) {

    this.tableId = id ? id : null;
    this.tableName = name ? name : '部门列表';
    let params: { pageNum: any; pageSize: any; parentId: any };
    params = {
      pageNum: this.pageIndex,
      pageSize: this.pageSize,
      parentId: this.tableId
    };
    if (this.tableId == null) {
      delete params.parentId;
    }

    this.systemService.depTreeTable(params).then(
      (response: any) => {
        this.tableInfos = response.data;
        this.total = response.recordsTotal;
      },
      reject => {
        console.log(reject);
      }
    );
  }

  search() {
    this.pageIndex = 1;
    this.loadPage();
  }

  loadPage() {
    this.tableInit(this.tableId, this.tableName);
  }

  ngOnInit() {
    this.systemService.depTree().then(
      (response: any) => {
        const node = response.data;
        this.nodes = this.createTreeData(node);
        const r = this.nodes.map((item: any) => {
          return this.expanded(item);
        });
        console.log(this.nodes);
      },
      reject => {
        console.log(reject);
      }
    );


    this.tableInit(this.tableId, this.tableName);
  }
}
